package chess;

import javax.swing.ImageIcon;
import javax.swing.JButton;
/**
 *
 * @author Alejandro
 */
public class Bishop extends Token{
    
    public Bishop (int column, int row, int color, JButton [][] board,
            Token [][] tokens){
        ImageIcon[] iconos = {new ImageIcon("src/imagenes/Scourge/balanar-A50.gif")
                        ,new ImageIcon("src/imagenes/Legion/magina-A50.gif")};
        this.setRow(row);
        this.setIcon(iconos);
        this.setColumn(column);
        this.setColor(color);
        this.board = board;
        this.setTokenOnBoard();
        this.tokens = tokens;
        this.setType("B");
    }

    @Override
    public void moveToken(int newColumn, int newRow){
        int R = this.getRow();
        int C = this.getColumn();
        try{
            boolean hit = checkHit(newColumn, newRow, C, R);
            if ((Math.abs(newRow - R) == Math.abs(newColumn - C)) &&
                    (!hit || enemy)){
                board[C][R].setIcon(null);
                this.setRow(newRow);
                this.setColumn(newColumn);
                this.setTokenOnBoard();
                this.setCorrectMove(true);
            }
            else{
                this.setCorrectMove(false);
            }
        }
        catch(Exception ex){
            this.setCorrectMove(false);
        }
    }
    
    private boolean checkHit(int newColumn, int newRow, int C, int R){
    int invertR;
    int invertC;
        if (newRow > R){
            invertR = 1;
            if (newColumn > C){
                invertC = 1;
            }
            else{
                invertC = -1;
            }
        }
        else{
            invertR = -1;
            if (newColumn > C){
                invertC = 1;
            }
            else{
                invertC = -1;
            }
        }
        for (int i = 1; R + i*invertR != newRow + invertR ||
                C + i*invertC != newColumn + invertC; i++){
            if (tokens[C+i*invertC][R+i*invertR] != null){
                if (tokens[C+i*invertC][R+i*invertR] == tokens[newColumn][newRow] &&
                    tokens[newColumn][newRow].getColor() != this.getColor()){
                    enemy = true;
                }
                else{
                    enemy = false;
                }
                return true;
            }
        }
        return false;
    } 
    
    private void setTokenOnBoard(){
        board[this.getColumn()][this.getRow()].setIcon(this.getIcon()[this.getColor()]);
    }
}